#include "stack.h"
#include <stdio.h>
#include <malloc.h>
mystack InitStack()
{
	mystack s;
	s.index = -1;
	s.capacity = INITLEN;
	s.data = (elem*)malloc(sizeof(elem)*INITLEN);
	s.mindata = (elem*)malloc(sizeof(elem)*INITLEN);
	return s;
}
int PushStack(mystack* this,elem e)
{
	int next=0;
	this->index = this->index + 1;
	next=this->index;
	if(next>this->capacity-1)//如果索引大于容量，则扩容两倍 
	{
		int i;
		elem* newData = (elem*)malloc(sizeof(elem)*this->capacity*2);
		elem* newMin = (elem*)malloc(sizeof(elem)*this->capacity*2);
		for(i=0;i<this->capacity;i++)
		{
			newData[i]=this->data[i];
			newMin[i]=this->mindata[i];
		}
		free(this->data);
		free(this->mindata);
		this->data=newData;
		this->mindata=newMin;
		this->capacity=this->capacity*2;
	}
	this->data[next] = e;
	if(next == 0)
	{
		this->mindata[next] = e;
	}
	else
	{
		if(this->mindata[next-1]>e)
		{
	 		this->mindata[next]=e;
		}
		else
		{
			this->mindata[next]=this->mindata[next-1];
		}
	}
	
}
int PopStack(mystack* this,elem *e)
{
	if(this->index<0){
		return 0;//失败 
	}
	*e=this->data[this->index--];
	return 1;//成功 
}
int GetStackLength(mystack* this)
{
	return this->index+1;
}
void DeleteStack(mystack* this)
{
	free(this->data);
	free(this->mindata);
	this->data=0;
	this->mindata=0;
}

int GetMin(mystack* this,elem *e)
{
	if(this->index<0){
		return 0;//失败 
	}
	*e=this->data[this->index];
	return 1;//成功 
}
void PrintStack(mystack* this)
{
	int i=0;
	printf("Stack sequence is:\n");
	for(i=0;i<=this->index;i++)
	{
		printf("%d ",this->data[i]);
	}
	printf("\n");
	printf("Stack Min sequence is:\n");
	for(i=0;i<=this->index;i++)
	{
		printf("%d ",this->mindata[i]);
	}
	printf("\n");
}
